<template>
  <el-row :gutter="10" class="user-page">
    <el-col :span="4" class="dept-content">
      <div class="title">部门结构</div>
      <el-tree
        v-loading="dataLoad"
        element-loading-text="部门树加载中"
        element-loading-spinner="el-icon-loading"
        empty-text="部门树为空"
        highlight-current
        accordion
        node-key="deptId"
        :data="deptTree"
        :props="deptTreeProps"
        :expand-on-click-node="false"
        @node-click="deptTreeClickHandle"
        @node-expand="deptTreeExpandHandle"
        ref="deptTree">
      </el-tree>
    </el-col>
    <el-col :span="20">
      <transition name="el-zoom-in-top">
        <el-form v-show="searchUserVisible" inline size="mini" :model="searchUserFrom" ref="searchUserForm" @keyup.enter.native="searchUserHandle">
          <el-form-item label="用户检索">
            <el-input v-model="searchUserFrom.word" clearable placeholder="请输入用户名称" ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchUserFrom.contact" clearable placeholder="请输入用户手机或者邮箱号" ></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchUserFrom.status" clearable placeholder="请选择用户状态" class="user-status-input">
              <el-option label="可用" value="0"></el-option>
              <el-option label="不可用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :disabled="dataLoad" @click="searchUserHandle" type="primary" plain
                       icon="el-icon-search">查询</el-button>
            <el-button :disabled="dataLoad" @click="resetUserPageHandle"
                       plain icon="el-icon-refresh-right">重置</el-button>
          </el-form-item>
        </el-form>
      </transition>

      <div class="u-tool">
        <el-button :disabled="dataLoad || !searchUserFrom.deptId " @click="$refs.userDialog.initUserDialog(searchUserFrom.deptId, deptName, undefined, false)"
                   type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
        <el-popover
          placement="top"
          width="200"
          trigger="hover">
          <p>您可以选择‘部门切换’模式</p>
          <div style="text-align: center; margin-top: 10px">
            <el-button :disabled="dataLoad || !searchUserFrom.deptId || totalNum === 0"
                       @click="openUserBatchMoveDialogHandle" type="success" size="mini" plain>
              批量
            </el-button>
            <el-button :disabled="dataLoad || !searchUserFrom.deptId || totalNum === 0"
                       @click="openUserMoveDialogHandle(undefined)" type="success" size="mini" plain>
              集体
            </el-button>
          </div>
          <el-button :disabled="dataLoad || !searchUserFrom.deptId || totalNum === 0" type="success" size="mini" plain
                     icon="el-icon-d-arrow-right" slot="reference">
            部门切换
          </el-button>
        </el-popover>
        <el-button :disabled="dataLoad || userTableSelected.length === 0" @click="deleteUserHandle(undefined)"
                   type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

        <span v-show="!!deptName" class="fz14 ml10">所属部门:</span>
        <span :style="{color: themeColor}" class="fz14">{{ deptName }}</span>
        <span v-show="!!deptName" @click="cancelDeptHandle" :style="{color: themeColor}" class="close-btn">
          <i class="el-icon-circle-close"></i>
        </span>

        <right-tool-bar :search-visible="searchUserVisible" :search-load="dataLoad"
                        @toggle-search="searchUserVisible = !searchUserVisible" @refresh-table="getUserList" />
      </div>

      <el-table
        v-loading="dataLoad"
        element-loading-text="用户数据加载中"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        :data="userList"
        :default-sort = "{ prop: searchUserFrom.field, order: searchUserFrom.order}"
        @sort-change="sortChangeHandle"
        @selection-change="val => this.userTableSelected = val"
        ref="userTable"
      >
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="deptName" header-align="center" align="center" label="所属部门"></el-table-column>
        <el-table-column sortable :sort-orders="sortOrders" prop="username" header-align="center" align="center" label="用户名称" width="100"></el-table-column>
        <el-table-column prop="phone" header-align="center" align="center" label="手机号" width="100"></el-table-column>
        <el-table-column prop="email" header-align="center" align="center" label="邮箱号"></el-table-column>
        <el-table-column prop="loginName" header-align="center" align="center" label="登录别名"></el-table-column>
        <el-table-column prop="status" header-align="center" align="center" label="状态">
          <template v-slot="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '可用' : '不可用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column sortable :sort-orders="sortOrders" prop="createTime" header-align="center" align="center" label="创建时间" width="135"></el-table-column>
        <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
        <el-table-column  label="操作" width="125">
          <template v-slot="scope">
            <el-button type="text" icon="el-icon-view" @click="$refs.userViewDialog.initUserViewDialog(scope.row.userId)">查看</el-button>

            <el-dropdown :disabled="loading">
              <span class="el-dropdown-link fz12" :style="{ color: themeColor, marginLeft: '7px' }">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-refresh-right" @click.native="openPasswordResetDialogHandle(scope.row)">
                  密码重置
                </el-dropdown-item>
                <el-dropdown-item divided  icon="el-icon-s-operation" size="small"
                           @click.native="$refs.userRoleModifyDialog.initUserRoleModifyDialog(scope.row)">
                  角色
                </el-dropdown-item>
                <el-dropdown-item divided icon="el-icon-d-arrow-right" @click.native="openUserMoveDialogHandle(scope.row)">
                  部门切换
                </el-dropdown-item>
                <el-dropdown-item icon="el-icon-s-operation" @click.native="openUserMoveViewDialogHandle(scope.row)">
                  切换记录
                </el-dropdown-item>
                <el-dropdown-item divided :icon="'el-icon-' + (scope.row.status === 0 ? 'close' : 'check')"
                                  @click.native="openDisableUserDialogHandle(scope.row, scope.row.status === 0)">
                  {{ scope.row.status === 0 ? '禁用' : '解禁' }}
                </el-dropdown-item>
                <el-dropdown-item divided icon="el-icon-edit" @click.native="$refs.userDialog.initUserDialog(searchUserFrom.deptId, deptName, scope.row, true)">
                  修改
                </el-dropdown-item>
                <el-dropdown-item icon="el-icon-delete" @click.native="deleteUserHandle(scope.row)">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格分页插件 -->
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalNum"
        :disabled="dataLoad"
        layout="total, sizes, prev, pager, next, jumper"
        class="paging">
      </el-pagination>

      <!-- 用户信息操作弹出框 -->
      <user-save-update ref="userDialog" @close-dialog="closeUserDialogHandle" />

      <!-- 系统用户密码重置弹出框 -->
      <user-password-reset :dialog-visible="passwordResetDialog" ref="passwordResetDialog"
                           @close-password-reset-dialog="passwordResetDialog = false" />

      <!-- 用户风控操作弹出框 -->
      <disable-user ref="disableUserDialog" @close-dialog="closeDisableUserDialogHandle" />

      <!-- 用户查看弹出框 -->
      <user-view ref="userViewDialog" />

      <!-- 用户切换部门弹出框 -->
      <user-move :dialog-visible="userMoveDialog" ref="userMoveDialog"
                 @close-user-move-dialog="closeUserMoveDialogHandle" />

      <!-- 用户批量切换部门弹出框 -->
      <user-batch-move :dialog-visible="userBatchMoveDialog" ref="userBatchMoveDialog"
                       @close-user-batch-move-dialog="closeUserBatchMoveDialogHandle" />

      <!-- 用户切换部门记录弹出框 -->
      <user-move-view :dialog-visible="userMoveViewDialog" ref="userMoveViewDialog"
                      @close-user-move-view-dialog="userMoveViewDialog = false" />

      <!-- 用户关联角色弹出框 -->
      <user-role-modify ref="userRoleModifyDialog" />

    </el-col>
  </el-row>

</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import UserSaveUpdate from "@/components/user/save-update";
  import UserPasswordReset from "@/components/user/update/password-reset.vue";
  import DisableUser from "@/components/risk/risk-user";
  import UserView from "@/components/user/view";
  import UserMove from "@/components/user/change-dept";
  import UserMoveView from "@/components/user/change-dept/view.vue";
  import UserBatchMove from "@/components/user/change-dept/batch.vue";
  import UserRoleModify from "@/components/role/role-user/modify.vue";

  export default {
    layout: 'admin',
    name: "admin-system-user",
    components: {
      RightToolBar, UserSaveUpdate, UserPasswordReset, DisableUser, UserView, UserMove, UserMoveView, UserBatchMove,
      UserRoleModify
    },
    data() {
      return {
        /*
          左侧数据
         */
        // 部门树数据
        deptTree: [],
        // 部门树节点属性值配置
        deptTreeProps: {
          children: 'children',
          label: 'deptName',
          disabled: 'disabled'
        },
        /*
          右侧数据
         */
        // 用户数据列表
        userList: [],
        // 角色表格被选中的‘行’数据
        userTableSelected: [],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 用户检索是否显示
        searchUserVisible: true,
        // 用户检索表单对象
        searchUserFrom: {
          // 部门主键
          deptId: undefined,
          // 用户名称
          word: '',
          // 用户联系方式，手机号或者邮箱号
          contact: '',
          // 用户状态
          status: '',
          // 排序字段
          field: 'createTime',
          // 排序方式
          order: 'ascending'
        },
        // 点击的部门节点名称
        deptName: undefined,
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前用户数量
        totalNum: 0,
        // 系统用户密码重置弹出框是否显示[true-显示 false-关闭]
        passwordResetDialog: false,
        // 用户切换部门弹出框是否显示[true-显示 false-关闭]
        userMoveDialog: false,
        // 用户批量切换部门弹出框是否显示[true-显示 false-关闭]
        userBatchMoveDialog: false,
        // 用户切换部门记录弹出框是否显示[true-显示 false-关闭]
        userMoveViewDialog: false,
      }
    },
    // asyncData({ app, params, query}) {
    //   return app.$axios.$post('/sys/user/list', { userType: true, page: 1, limit: 10, field: 'username', order: 'ascending' })
    //     .then(data => {
    //       return {
    //         userList: data.page.list,
    //         totalNum: data.page.totalNum
    //       }
    //     })
    //     .catch(() => {})
    // },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    created() {
      if (process.client) {

        this.getDeptTree()

        this.getUserList()
      }
    },
    methods: {
      /**
       * 获取部门树数据方法
       */
      getDeptTree() {
        this.$axios.$get("/sys/dept/children/tree")
          .then(({ data }) => {
            this.deptTree.push(data);
          })
          .catch(() => {})
      },
      /**
       * 部门树节点点击事件
       * @param {Object} dept 部门对象
       */
      deptTreeClickHandle(dept) {
        if (this.dataLoad) {
          this.notify('', '温馨提示', '用户数据正在加载中，请稍后再点击');
        }
        const searchUserFrom = this.searchUserFrom;
        if (searchUserFrom.deptId === dept.deptId) {
          return
        }
        searchUserFrom.deptId = dept.deptId;
        this.deptName = dept.deptName;

        this.getUserList();
      },
      /**
       * 部门树节点展开事件
       * @param {Object} dept 部门对象
       */
      deptTreeExpandHandle(dept) {
        let queue = [ dept.children ]
        while (queue.length > 0) {
          let array = queue.shift();

          for (let childrenDept of array) {
            // 展开 子节点 操作
            this.$refs.deptTree.store.nodesMap[childrenDept.deptId].expanded = true;

            if (!!childrenDept.children) {
              queue.push(childrenDept.children)
            }
          }
        }
      },
      /**
       * 取消选中部门事件
       */
      cancelDeptHandle() {
        const searchUserFrom = this.searchUserFrom;
        searchUserFrom.deptId = undefined;
        this.deptName = undefined;

        this.pageIndex = 1;

        this.getUserList();
      },
      // 用户检索事件
      searchUserHandle() {
        this.pageIndex = 1

        this.getUserList()
      },
      /**
       * 获取用户数据方法
       */
      getUserList() {
        let searchUserFrom = this.searchUserFrom;
        let obj = {
          deptId: searchUserFrom.deptId,
          word: searchUserFrom.word,
          contact: searchUserFrom.contact,
          status: searchUserFrom.status,
          field: searchUserFrom.field,
          order: searchUserFrom.order,
          page: this.pageIndex,
          limit: this.pageSize
        }
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/sys/user/page/list', obj)
          .then(({ data:page }) => {
            this.userList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      // 每页显示个数变化事件
      sizeChangeHandle(size) {
        this.pageIndex = 1
        this.pageSize = size
        this.getUserList()
      },
      // '点击特定页码'、'上一页'、'下一页'操作事件
      currentChangeHandle(index) {
        if (this.pageIndex === index) {
          return
        }
        this.pageIndex = index
        this.getUserList()
      },
      // 表格选择字段排序事件
      sortChangeHandle( { prop, order } ) {
        this.pageIndex = 1
        this.searchUserFrom.field = prop
        this.searchUserFrom.order = order

        this.getUserList()
      },
      /**
       * 打开用户风控弹出框事件
       * @param user    被操作风控的用户对象
       * @param optType 操作类型[true-风控 false-解除风控]
       */
      openDisableUserDialogHandle(user, optType) {
        this.$refs.disableUserDialog.initDisableUserDialog(user, optType)
      },
      /**
       * 关闭用户风控操作弹出框事件
       * @param bool 操作结果[true-成功 false-取消]
       */
      closeDisableUserDialogHandle(bool) {
        if (bool) {
          this.getUserList()
        }
      },
      /**
       * 打开用户切换部门弹出框事件
       * @param {Object} user 用户对象
       */
      openUserMoveDialogHandle(user) {
        this.userMoveDialog = true;

        this.$nextTick(() => {
          this.$refs.userMoveDialog.initUserMoveDialog(user, this.searchUserFrom.deptId, this.deptName);
        })
      },
      /**
       * 关闭用户切换部门弹出框事件
       * @param {boolean} bool 是否刷新表格数据
       */
      closeUserMoveDialogHandle(bool) {
        this.userMoveDialog = false

        if (bool) {
          this.getUserList()
        }
      },
      /**
       * 打开批量用户切换部门弹出框事件
       */
      openUserBatchMoveDialogHandle() {
        this.userBatchMoveDialog = true;

        this.$nextTick(() => {
          this.$refs.userBatchMoveDialog.initUserBatchMoveDialog(this.searchUserFrom.deptId, this.deptName);
        })
      },
      /**
       * 关闭批量用户切换部门弹出框事件
       */
      closeUserBatchMoveDialogHandle() {
        this.userBatchMoveDialog = false;

        this.getUserList()
      },
      /**
       * 打开用户切换部门记录弹出框事件
       * @param {Object} user 用户对象
       */
      openUserMoveViewDialogHandle(user) {
        this.userMoveViewDialog = true;

        this.$nextTick(() => {
          this.$refs.userMoveViewDialog.initUserMoveViewDialog(user);
        })
      },
      /**
       * 删除用户事件
       * @param user 用户对象（只有单个删除时，该参数才有值）
       */
      deleteUserHandle(user) {
        // 所有要删除的用户id
        let userIds = []
        // 所有要删除的用户名字
        let userName = []
        if (!user) {
          this.userTableSelected.forEach(user => {
            userIds.push(user.userId);
            userName.push(user.username);
          })
        } else {
          userIds.push(user.userId);
          userName.push(user.username);
        }

        this.$confirm(`确定删除${userName}用户吗?`, '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮不可被点击
          this.dataLoad = true
          this.$axios.$delete('/sys/user/delete', { data: userIds })
            .then(() => {
              this.notify('success', '操作成功', `${userName}用户删除成功`);

              // 重新获取角色列表
              this.getUserList()
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.dataLoad = false
            })

        }).catch(() => {})
      },
      // 关闭用户操作弹出框事件
      closeUserDialogHandle(bool) {
        if (bool) {
          this.getUserList()
        }
      },
      // 打开用户操作弹出框事件
      /**
       * 打开系统用户密码重置弹出框事件
       * @param {Object} sysUser 系统用户信息
       */
      openPasswordResetDialogHandle(sysUser) {
        this.passwordResetDialog = true

        this.$nextTick(() => {
          this.$refs.passwordResetDialog.initSysUserDialogHandle(sysUser)
        })
      },
      // 重置页面事件
      resetUserPageHandle() {
        this.deptName = undefined;
        this.searchUserFrom = {
          deptId: undefined,
          word: '',
          contact: '',
          status: '',
          field: 'createTime',
          order: 'ascending'
        }
        this.pageIndex = 1
        this.pageSize = 10
        // console.log("表单对象: ", this.searchUserFrom)
      }

    }
  }
</script>

<style scoped>
  .user-page .dept-content .title {
    margin-bottom: 7px;
  }
  .user-page .user-status-input {
    width: 140px;
  }
  .user-page .u-tool {
    margin-bottom: 7px;
  }
  .user-page .u-tool .close-btn {
    --color: black;
    margin-left: 7px;
    cursor: pointer;
    color: var(--color);
  }
  .user-page .paging {
    float: right;
    margin: 7px;
  }
</style>
